package com.leosmart

import android.annotation.SuppressLint
import android.app.Application
import android.content.res.Configuration
import android.os.Build
import com.facebook.react.PackageList
import com.facebook.react.ReactApplication
import com.facebook.react.ReactHost
import com.facebook.react.ReactNativeHost
import com.facebook.react.ReactPackage
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load
import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost
import com.facebook.react.defaults.DefaultReactNativeHost
import com.facebook.react.soloader.OpenSourceMergedSoMapping
import com.facebook.soloader.SoLoader
import com.nativelaunchmanager.NativeLaunchManagerPackage
import com.nativeringing.NativeRingingPackage
import com.nativescan.NativeScanPackage
import com.nativetoast.NativeToastPackage
import com.otahotupdate.OtaHotUpdate


class MainApplication : Application(), ReactApplication {

  override val reactNativeHost: ReactNativeHost =
      object : DefaultReactNativeHost(this) {
        override fun getPackages(): List<ReactPackage> =
            PackageList(this).packages.apply {
              // Packages that cannot be autolinked yet can be added manually here, for example:
              // add(MyReactNativePackage())
                addAll(listOf(
                  NativeScanPackage(),
                  NativeRingingPackage(),
                  NativeToastPackage(),
                  NativeLaunchManagerPackage()
                ))
            }

        override fun getJSMainModuleName(): String = "index"
        override fun getJSBundleFile(): String? {
          return OtaHotUpdate.bundleJS(this@MainApplication)
        }
        override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG

        override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED
        override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED
      }

  override val reactHost: ReactHost
    get() = getDefaultReactHost(applicationContext, reactNativeHost)
  @SuppressLint("WrongConstant")
  private fun enforceFixedDensity() {
    val metrics = resources.displayMetrics
    val config: Configuration = resources.configuration


    // 设置为固定密度（以 160dpi 为基准）
    val targetDensity = 2.8625f // 1.0 = 160dpi
    val targetDensityDpi = 458

    metrics.density = targetDensity
    metrics.scaledDensity=targetDensity // 禁用字体缩放
    metrics.densityDpi = targetDensityDpi

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
      config.densityDpi = targetDensityDpi
    }

    resources.updateConfiguration(config, metrics)
  }
  override fun onCreate() {
    super.onCreate()
//    enforceFixedDensity()
    SoLoader.init(this, OpenSourceMergedSoMapping)
    if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
      // If you opted-in for the New Architecture, we load the native entry point for this app.
      load()
    }
  }
}
